/*
 * Copyright (c) 2018. cangoonline.net All Rights Reserved.
 * 类名称：MailSerderImpl.java
 * 创建人：韩伟
 * 联系方式：hanwei@cangoonline.com
 */
package com.cango.mail.impl;

import com.cango.framework.base.dao.IBaseDao;
import com.cango.framework.base.util.Container;
import com.cango.mail.CangoMail;
import com.cango.mail.MailSender;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Author: hanwei
 * CreateDate: 2019/9/11
 */
@Service
public class MailSerderImpl implements MailSender {
    Logger logger = LoggerFactory.getLogger(MailSerderImpl.class);
    @Resource(name = "basedao")
    private IBaseDao baseDao;

    @Override
    public void sendMail() {
        Lock lock = new ReentrantLock();

        try {
            lock.lock();
            List<CangoMail> list = queryPendingMails(200);
            if(null != list && !list.isEmpty()){
                for(CangoMail mail : list){
                    sendOneMail(mail);
                }
            }

        }catch (Exception e){
            logger.error("批量发送邮件失败",e);
        }finally {
            lock.unlock();
        }
    }

    private void sendOneMail(CangoMail mail){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("id",mail.getId());
        try {

            SimpleMailMessage msg = new SimpleMailMessage();
            String mailto = mail.getMailto();
            String cc = mail.getCc();
            String bcc= mail.getBcc();
            mailto = mailto.replaceAll("；", ";");
            msg.setTo(mailto.split(";"));
            if(StringUtils.isNotEmpty((cc))){
                msg.setCc(cc.split(";"));
            }
            if(StringUtils.isNotEmpty((bcc))){
                msg.setBcc(bcc.split(";"));
            }




            msg.setText(mail.getContent());

            String title = mail.getSubject();
            msg.setSubject(title);
            msg.setFrom(mail.getFrom());
            com.cango.framework.base.job.MailSender sender = Container.getBean("mailSender", com.cango.framework.base.job.MailSender.class);
            sender.sendMail(msg);

            //发送成功
            map.put("sendflg","1");
            map.put("remark","");
            baseDao.update("mail.updatePendingMail",map);
        }catch (Exception e){
            logger.warn("发送单封邮件失败",e);
            //发送失败
            map.put("sendflg","2");
            String msg = ExceptionUtils.getMessage(e);
            if(msg.length()>500){
                msg = msg.substring(0,499);
            }
            map.put("remark",msg);
            baseDao.update("mail.updatePendingMail",map);
        }
    }

    /**
     * 查询未发送出的邮件记录
     * @param pendingCnt
     * @return
     */
    private List<CangoMail> queryPendingMails(int pendingCnt){
        return baseDao.queryList("mail.selectPendingMails",pendingCnt);
    }
}
